package com.hurt.competition.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class FileUtil {

    public static Set<String> containsExt = new HashSet<>();
    public static Map<String,String> contentTypeMap = new HashMap<>();

    static {
        containsExt.add("pdf");
        containsExt.add("jpg");
        containsExt.add("jpeg");
        containsExt.add("png");

        contentTypeMap.put("png","image/jpeg");
        contentTypeMap.put("jpg","image/jpeg");
        contentTypeMap.put("jpeg","image/jpeg");
        contentTypeMap.put("pdf","application/pdf");
    }

    public static boolean validFileExt(MultipartFile file){
        String fileName = file.getOriginalFilename();

        String ext = fileName.substring(fileName.indexOf(".")+1, fileName.length());
        if(containsExt.contains(ext)){
            return true;
        }

        return false;
    }

    public static String getFileExtension(String fileName) {
        if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".")+1);
        } else {
            return "";
        }
    }

    public static String switchContentType(String fileName) {
        String contentType = contentTypeMap.get(getFileExtension(fileName));
        return StringUtils.isBlank(contentType)?"":contentType;
    }
}
